﻿using System;
using System.Runtime.Serialization;
using System.Threading;

namespace MSPToolkit.Utilities
{
    /// <summary>
    /// IsolatedStorageHelper helps easely save/load data to/from Isolated Storage
    /// </summary>
    public static class IsolatedStorageHelper
    {
        public static Mutex rwMutex = new Mutex(false, "IsolatedStorageHelperMutex");

        /// <summary>
        /// Saves object to %fileName% using DataContractSerializer
        /// If %fileName% doesn't exist, it crates one, ore replace if exist
        /// </summary>
        /// <param name="obj">Object of Knowing type</param>
        /// <param name="fileName">File Name in Isolated Storage to save</param>
        /// <typeparam name="T">serializable type</typeparam>
        public static void SaveSerializableObject<T>(T obj, string fileName)
        {
            rwMutex.WaitOne();            
            System.IO.IsolatedStorage.IsolatedStorageFile f = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            try
            {
                using (var stream = f.OpenFile(fileName, System.IO.FileMode.Create))
                {
                    var dcs = new DataContractSerializer(typeof(T));
                    dcs.WriteObject(stream, obj);
                    stream.Close();
                }
            }
            finally
            {
                f.Dispose();
                rwMutex.ReleaseMutex();
            }

        }

        /// <summary>
        /// Load object from Isolated Storage using DataContractSerializer
        /// </summary>
        /// <param name="fileName">Name of existing file in Isolated Storage</param>
        /// <returns>Loaded object of T</returns>
        /// <typeparam name="T">serializable type</typeparam>
        public static T LoadSerializableObject<T>(string fileName)
        {
            rwMutex.WaitOne();
            System.IO.IsolatedStorage.IsolatedStorageFile f = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            try
            {
                var dcs = new DataContractSerializer(typeof(T));
                T obj;
                if (!f.FileExists(fileName))
                {
                    throw new System.IO.FileNotFoundException();
                }
                using (var stream = f.OpenFile(fileName, System.IO.FileMode.Open))
                {
                    obj = (T)dcs.ReadObject(stream);
                    stream.Close();
                    return obj;
                }
            }
            finally
            {                
                f.Dispose();
                rwMutex.ReleaseMutex();
            }
            
        }
    }
}
